package com.sky.task;

import com.sky.mapper.user.UserOrderMapper;
import com.sky.pojo.Orders;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class CheckOrderPayStatus {
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private Config config;
/*
    @Scheduled(cron = "0 0/1 * * * ?")
*/
    public void checkPayStatus(){
        log.info("检查订单支付状态,任务开始");
        //找15分钟前的订单
        LocalDateTime before15Min = LocalDateTime.now().minusMinutes(15);
        log.info("查询时间:{}",before15Min);
        List<Orders> checkPayStatusOrders = userOrderMapper.getCheckPayStatusOrders(before15Min);
        if (CollectionUtils.isEmpty(checkPayStatusOrders)){
            log.info("没有需要处理的订单");
            return;
        }
        for (Orders order : checkPayStatusOrders){
            Boolean flag=getPayStatus(order.getNumber());
            //判断支付状态
            if (flag){
                order.setStatus(Orders.TO_BE_CONFIRMED);
                order.setPayStatus(Orders.PAID);
                userOrderMapper.updateOrderPaySuccess(order);
            }else {
                order.setStatus(Orders.CANCELLED_ORDER);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("支付超时");
                userOrderMapper.cancelOrder(order);
            }
        }
    }

    private Boolean getPayStatus(String number) {
        try {
            QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
            request.setMchid("1561414331");
            request.setOutTradeNo(number);
            NativePayService payService = new NativePayService.Builder().config(config).build();
            Transaction transaction = payService.queryOrderByOutTradeNo(request);
            log.info("调用微信查询接口返回:{}",transaction);
            if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
                return true;
            }
        } catch (ServiceException e) {
            if (e.getErrorCode().equals("ORDER-NOT-EXISTS")){
                log.error("微信订单不存在");
                return false;
            }
        }
        return false;
    }
}
